package com.fdhwws.web.servlet.api;

import com.fdhwws.web.domain.ChatRoom;
import com.fdhwws.web.domain.User;
import com.fdhwws.web.entity.AjaxResult;
import com.fdhwws.web.service.ChatRoomService;
import com.fdhwws.web.service.impl.ChatRoomServiceImpl;
import com.fdhwws.web.servlet.BaseServlet;
import com.fdhwws.web.util.InfoSecurityUtil;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.annotation.WebServlet;
import org.apache.commons.fileupload2.core.DiskFileItem;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.jakarta.JakartaServletDiskFileUpload;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

@WebServlet("/api/chatroom/*")
public class ChatRoomAPIServlet extends BaseServlet {
    private final ChatRoomService chatRoomService = new ChatRoomServiceImpl();

    public AjaxResult createNewChatRoom(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        User user = (User) ajaxResult.data;
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setValid(true);
        chatRoom.setCreateTime(new Timestamp(System.currentTimeMillis()));
        chatRoom.setCreateUserId(user.getId());
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory.Builder().get();
        JakartaServletDiskFileUpload jakartaServletDiskFileUpload = new JakartaServletDiskFileUpload(diskFileItemFactory);
        jakartaServletDiskFileUpload.setHeaderCharset(StandardCharsets.UTF_8);
        List<DiskFileItem> diskFileItems = jakartaServletDiskFileUpload.parseRequest(httpUtil.getRequest());
        for (DiskFileItem diskFileItem : diskFileItems) {
            String fieldName = diskFileItem.getFieldName();
            String fieldValue = diskFileItem.getString(StandardCharsets.UTF_8);
            if (diskFileItem.isFormField()) {
                switch (fieldName) {
                    case "name":
                        chatRoom.setName(fieldValue);
                        Boolean b = chatRoomService.checkChatRoom(fieldValue);
                        if (!b) {
                            return AjaxResult.error("房间名已存在", null);
                        }
                        break;
                    case "password":
                        chatRoom.setPassword(fieldValue);
                        break;
                    case "access":
                        chatRoom.setAccess(Integer.parseInt(fieldValue));
                        break;
                }
            } else {
                if (fieldName.equals("pic")) {
                    String filePath = "static/img/pics/" + UUID.randomUUID() + ".png";
                    String realPath = getServletContext().getRealPath("/" + filePath);
                    File file = new File(realPath);
                    if (!file.getParentFile().exists()) {
                        file.mkdirs();
                    }
                    file.createNewFile();
                    diskFileItem.write(file.toPath());
                    chatRoom.setPic(filePath);
                    diskFileItem.delete();
                }
            }
        }
        if (chatRoom.getPic() == null) {
            chatRoom.setPic("static/img/暂无图片.png");
        }
        if (chatRoom.getAccess() == 1) {
            chatRoom.setPassword(null);
        }
        return chatRoomService.addChatRoom(chatRoom, user);
    }

    public AjaxResult getChatRoomByUid(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        User user = (User) ajaxResult.data;
        List<ChatRoom> chatRoomByUid = chatRoomService.getChatRoomByUid(user.getId());
        if (chatRoomByUid != null) {
            Stream<ChatRoom> chatRoomStream = chatRoomByUid.stream().filter(chatRoom -> {
                chatRoom.safeMode(true);
                return chatRoom.getValid();
            });
            chatRoomByUid = chatRoomStream.toList();
        } else {
            chatRoomByUid = new ArrayList<>();
        }
        return AjaxResult.success("查询成功", chatRoomByUid);
    }

    public AjaxResult getAllChatRoom(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        List<ChatRoom> allChatRoom = chatRoomService.getAllChatRoom();
        Stream<ChatRoom> chatRoomStream = allChatRoom.stream().filter(chatRoom -> {
            chatRoom.safeMode(false);
            return chatRoom.getValid();
        });
        allChatRoom = chatRoomStream.toList();
        return AjaxResult.success("查询成功", allChatRoom);
    }

    public AjaxResult getAllChatRoom_admin(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyAdminUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        List<ChatRoom> allChatRoom = chatRoomService.getAllChatRoom();
        return AjaxResult.success("查询成功", allChatRoom);
    }

    public AjaxResult getChatRoomByRoomId(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        try {
            Number roomId = httpUtil.getNumberParameter("roomId");
            AjaxResult chatRoomByRoomId = chatRoomService.getChatRoomByRoomId(roomId.intValue());
            if (chatRoomByRoomId.isSuccess()) {
                ChatRoom data = (ChatRoom) chatRoomByRoomId.data;
                if (!data.getValid()) {
                    return AjaxResult.error("无此房间", null);
                }
                chatRoomByRoomId.data = data.safeMode(false);
            }
            return chatRoomByRoomId;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("房间号错误", null);
        }
    }

    public AjaxResult getChatRoomByRoomId_admin(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyAdminUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        try {
            Number roomId = httpUtil.getNumberParameter("roomId");
            return chatRoomService.getChatRoomByRoomId(roomId.intValue());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("房间号错误", null);
        }
    }

    public AjaxResult delChatRoomByRoomId(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        User user = (User) ajaxResult.data;
        try {
            Number roomId = httpUtil.getNumberParameter("roomId");
            return chatRoomService.deleteChatRoomById(roomId.intValue(), user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("房间号错误或无权限", null);
        }
    }

    public AjaxResult openOrCloseChatRoom_admin(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyAdminUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        try {
            Number roomId = httpUtil.getNumberParameter("roomId");
            return chatRoomService.openOrCloseChatRoomByRoomId(roomId.intValue());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("房间号错误", null);
    }

    public AjaxResult updateChatRoomByRoomId(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory.Builder().get();
        JakartaServletDiskFileUpload jakartaServletDiskFileUpload = new JakartaServletDiskFileUpload(diskFileItemFactory);
        jakartaServletDiskFileUpload.setHeaderCharset(StandardCharsets.UTF_8);
        List<DiskFileItem> diskFileItems = jakartaServletDiskFileUpload.parseRequest(httpUtil.getRequest());
        ChatRoom chatRoom = new ChatRoom();
        try {
            for (DiskFileItem diskFileItem : diskFileItems) {
                String fieldName = diskFileItem.getFieldName();
                String fieldValue = diskFileItem.getString(StandardCharsets.UTF_8);
                if (diskFileItem.isFormField()) {
                    switch (fieldName) {
                        case "id":
                            if (!StringUtils.isNullOrEmpty(fieldValue)) {
                                chatRoom.setId(Integer.parseInt(fieldValue));
                            }
                            break;
                        case "name":
                            if (!StringUtils.isNullOrEmpty(fieldValue)) {
                                chatRoom.setName(fieldValue);
                            }
                            break;
                        case "password":
                            if (!StringUtils.isNullOrEmpty(fieldValue)) {
                                chatRoom.setPassword(fieldValue);
                            }
                            break;
                        case "access":
                            if (!StringUtils.isNullOrEmpty(fieldValue)) {
                                chatRoom.setAccess(Integer.parseInt(fieldValue));
                            }
                            break;
                    }
                } else {
                    if (fieldName.equals("pic")) {
                        String filePath = "static/img/pics/" + UUID.randomUUID() + ".png";
                        String realPath = getServletContext().getRealPath("/" + filePath);
                        File file = new File(realPath);
                        if (!file.getParentFile().exists()) {
                            file.mkdirs();
                        }
                        file.createNewFile();
                        diskFileItem.write(file.toPath());
                        chatRoom.setPic(filePath);
                        diskFileItem.delete();
                    }
                }
            }
        } catch (NumberFormatException e) {
            return AjaxResult.error("房间号不合法", null);
        }
        System.out.println(chatRoom);
        return chatRoomService.updateChatRoom(chatRoom);
    }
}
